package com.yuyou.train.user.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

import org.slf4j.Logger;  import org.slf4j.LoggerFactory;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yuyou.train.service.api.lesson.entity.LessonClass;
import com.yuyou.train.service.api.lesson.service.LessonAPI;
import com.yuyou.train.service.api.user.dto.MyCommentPageDTO;
import com.yuyou.train.service.api.user.dto.UserCommentPageDTO;
import com.yuyou.train.service.api.user.dto.UserLessonClassCommentPageDTO;
import com.yuyou.train.service.api.user.dto.UserLessonCommentDTO;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.entity.UserComment;
import com.yuyou.train.user.service.IUserCommentService;
import com.yuyou.train.user.service.IUserService;
import com.yuyou.train.user.vo.req.ReqCommentAdd;
import com.yuyou.train.user.vo.resp.RespCommentOnLessonClass;
import com.yuyou.train.util.bean.LoginRedisObj;
import com.yuyou.train.util.bean.PageParams;
import com.yuyou.train.util.bean.Pagination;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.bean.ReturnResult;
import com.yuyou.train.util.enums.user.UserCommentEnums;
import com.yuyou.train.util.tool.DefindBeanUtils;


@Validated
@RestController
@RequestMapping(value="/api/userComment")
public class UserCommentController extends BaseController{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private IUserCommentService userCommentService;

	@Autowired
	private IUserService userService;

	@Autowired
	private LessonAPI lessonAPI;
	
	@ApiOperation(value="评论、课程点评的分页列表")
	@RequestMapping(value="/findCommentPage",method = RequestMethod.POST)
	public ReturnResult<Pagination<UserCommentPageDTO>> findUserCommentPage(@Validated @ModelAttribute PageParams pageParams,
																			@NotNull@ApiParam(value = "0:评论, 1:课程点评",required = true) @RequestParam(value = "type") Integer type,
																			@ApiParam(value = "1：通过：2不通过") @RequestParam( value = "verifyStatus", required = false) String verifyStatus,
																			@RequestParam(value = "startTime", required = false) String startTime,
																			@RequestParam(value = "endTime", required = false)String endTime){
		Map<String, Object> conditions=new HashMap<>();
		Pagination<UserCommentPageDTO> queryPgn = new Pagination<>();
		conditions.put("verifyStatus", verifyStatus);
		conditions.put("startTime", startTime);
		conditions.put("endTime", endTime);
		String[] types = null;
		if(0 == type){
			types = new String[]{"01", "02","04"};
		}
		if(1 == type){
			types = new String[]{"03"};
		}
		conditions.put("types", types);
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = userCommentService.findUserCommentPageCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total>0){
			queryPgn.setTotal(total);
			List<UserCommentPageDTO> list = userCommentService.findUserCommentPageList(queryPgn);
			queryPgn.setList(list);
		}
		return ReturnResult.success(queryPgn);
	}

	@ApiOperation(value="我的评论(前台)")
	@RequestMapping(value="/myCommentPage",method = RequestMethod.POST)
	public ReturnResult<Pagination<MyCommentPageDTO>> myCommentPage(@Validated @ModelAttribute PageParams pageParams,
																	HttpServletRequest request){

		LoginRedisObj loginObj = this.getUserObj(request);
		Map<String, Object> conditions=new HashMap<>();
		Pagination<MyCommentPageDTO> queryPgn = new Pagination<>();
		conditions.put("userId", loginObj.getUserId());

		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = userCommentService.findMyCommentPageCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			queryPgn.setTotal(total);
			List<MyCommentPageDTO> list = userCommentService.findMyCommentPage(queryPgn);
			queryPgn.setList(list);
		}
		return ReturnResult.success(queryPgn);
	}

	@ApiOperation(value="小伙伴(对我)的评论(前台)")
	@RequestMapping(value="/commentOnMePage",method = RequestMethod.POST)
	public ReturnResult<Pagination<MyCommentPageDTO>> commentOnMePage(@Validated @ModelAttribute PageParams pageParams,
																	  HttpServletRequest request){

		LoginRedisObj loginObj = this.getUserObj(request);
		Map<String, Object> conditions = new HashMap<>();
		Pagination<MyCommentPageDTO> queryPgn = new Pagination<>();
		conditions.put("parentId", loginObj.getUserId());

		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = userCommentService.findCommentOnMePageCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			queryPgn.setTotal(total);
			List<MyCommentPageDTO> list = userCommentService.findCommentOnMePage(queryPgn);
			queryPgn.setList(list);
		}
		return ReturnResult.success(queryPgn);
	}


	@ApiOperation(value="班级评论（前台）")
	@RequestMapping(value="/findClassCommentPage",method = RequestMethod.POST)
	public ReturnResult<UserLessonClassCommentPageDTO> findClassCommentPage(@Validated @ModelAttribute PageParams pageParams,
																			HttpServletRequest request,
																			@ApiParam(value = "班级 id") @RequestParam( value = "lessonClassId", required = false) String lessonClassId){

		if(null == lessonClassId){
			LoginRedisObj loginObj = this.getUserObj(request);
			User user = userService.selectByPrimaryKey(loginObj.getUserId());
			lessonClassId = user.getClassId();
		}

		UserLessonClassCommentPageDTO userLessonClassCommentPageDTO = new UserLessonClassCommentPageDTO();

		Map<String, Object> conditions = new HashMap<>();
		Pagination<UserCommentPageDTO> queryPgn = new Pagination<>();
		conditions.put("foreignId", lessonClassId);
		conditions.put("verifyStatus", UserCommentEnums.verifyStatus.success.getValue());
		conditions.put("type", UserCommentEnums.type._class.getValue());
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = userCommentService.findUserCommentPageCount(queryPgn);
		int sumStar = userCommentService.sumStar(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			queryPgn.setTotal(total);
			List<UserCommentPageDTO> list = userCommentService.findUserCommentPageList(queryPgn);
			queryPgn.setList(list);
		}

		userLessonClassCommentPageDTO.setTotalUser(total);
		userLessonClassCommentPageDTO.setAvgStar(0 == total ? 0 : (sumStar/total));
		userLessonClassCommentPageDTO.setUserCommentPagePagination(queryPgn);
		return ReturnResult.success(userLessonClassCommentPageDTO);
	}

	@ApiOperation(value="课程评论（前台）")
	@RequestMapping(value="/findLessonCommentPage",method = RequestMethod.POST)
	public ReturnResult<Pagination<UserLessonCommentDTO>> findLessonCommentPage(@Validated @ModelAttribute PageParams pageParams,
																				@ApiParam(value = "课程 id") @RequestParam( value = "lessonId", required = true) String lessonId,
																				HttpServletRequest request){

		LoginRedisObj loginObj = this.getUserObj(request);

		Map<String, Object> conditions = new HashMap<>();
		Pagination<UserLessonCommentDTO> queryPgn = new Pagination<>();
		conditions.put("foreignId", lessonId);
		conditions.put("verifyStatus", UserCommentEnums.verifyStatus.success.getValue());
//		conditions.put("type", UserCommentEnums.type.lesson.getValue());
		conditions.put("level", 1);
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = userCommentService.findUserLessonCommentPageCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			queryPgn.setTotal(total);
			List<UserLessonCommentDTO> list = userCommentService.findUserLessonCommentPageList(queryPgn, loginObj.getUserId());
			queryPgn.setList(list);
		}

		return ReturnResult.success(queryPgn);
	}


	@ApiOperation(value="我的评论->课程评分(前台)")
	@RequestMapping(value="/myCommentOnLessonClass",method = RequestMethod.POST)
	public ReturnResult<List<RespCommentOnLessonClass>> myCommentOnLessonClass(HttpServletRequest request){
		List<RespCommentOnLessonClass> commentOnLessonClassList = new ArrayList<>();

		RespCommentOnLessonClass commentOnLessonClass = new RespCommentOnLessonClass();

		LoginRedisObj loginObj = this.getUserObj(request);
		User user = userService.selectByPrimaryKey(loginObj.getUserId());

		// 班级信息
		LessonClass lessonClass = lessonAPI.findLessonClassById(user.getClassId());

		// 评论信息
		UserComment userComment = new UserComment();
		userComment.setUserId(user.getId());
		userComment.setForeignId(lessonClass.getId());
		userComment.setType(UserCommentEnums.type._class.getValue());
		List<UserLessonCommentDTO> userCommentQuery = userCommentService.findUserComment(userComment);
		if(!CollectionUtils.isEmpty(userCommentQuery)){
			DefindBeanUtils.copyProperties(lessonClass, commentOnLessonClass);
			// 一个班级一个人只有一条评论
			DefindBeanUtils.copyProperties(userCommentQuery.get(0), commentOnLessonClass);
		}
		commentOnLessonClassList.add(commentOnLessonClass);
		return ReturnResult.success(commentOnLessonClassList);
	}


	@ApiOperation(value="审核评论、课程点评")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "ids", value = "评论ID列表（多个逗号分隔）", paramType="query", required = true),
		@ApiImplicitParam(name = "verifyStatus", value = "审核状态：1：通过：2不通过", paramType="query",required = true)}
		)
	@RequestMapping(value="/verComment",method=RequestMethod.POST)
	public ReturnResult<ResBoolSimpleInfo> verComment(
			@NotEmpty (message="评论ID列表(ids)不能为空") @RequestParam(value="ids") List<String> ids,
			@RequestParam(value = "verifyStatus" ) String verifyStatus){
		userCommentService.verComment(ids, verifyStatus);
		return ReturnResult.success();
	}
	
	@ApiOperation(value="删除评论、课程点评")
	@ApiImplicitParam(name = "id", value = "评论ID", paramType="query", required = true)
	@RequestMapping(value="/delComment",method = RequestMethod.POST)
	public ReturnResult<ResBoolSimpleInfo> delComment(@NotBlank (message="id不能为空") String id){
		userCommentService.deleteCommentWithChildren(id);
		return ReturnResult.success();
	}
	
	
	@ApiOperation(value="下拉评论列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "foreignId", value = "（感想，资源，班级）ID", paramType="query", required = true),
		@ApiImplicitParam(name = "start", value = "开始条数", paramType="query", required = true),
		@ApiImplicitParam(name = "limit", value = "下拉条数", paramType="query",required = true)}
		)
	@RequestMapping(value="/findCommentLimit",method=RequestMethod.POST)
	public ReturnResult<List<UserComment>> findCommentLimit(
			@NotBlank (message="foreignId不能为空") String foreignId,
			@NotBlank (message="start不能为空") Integer start, 
			@NotBlank (message="limit不能为空") Integer limit){
		List<UserComment>  list = userCommentService.finduserCommentLimit(foreignId, start, limit);
		return ReturnResult.success(list);
	}

	
	@ApiOperation(value="发表评论(前台)")
	@RequestMapping(value="/addComment",method=RequestMethod.POST)
	public ReturnResult<UserComment> addComment(@Validated @ModelAttribute ReqCommentAdd reqCommentAdd,
													  HttpServletRequest request) throws Exception {
		LoginRedisObj loginObj = this.getUserObj(request);
		User user = userService.selectByPrimaryKey(loginObj.getUserId());
		UserComment userComment = new UserComment();
		DefindBeanUtils.copyProperties(reqCommentAdd, userComment);
		if(UserCommentEnums.type._class.getValue().equals(userComment.getType())){
			userComment.setVerifyStatus(UserCommentEnums.verifyStatus.pending.getValue());
		}else{
			userComment.setVerifyStatus(UserCommentEnums.verifyStatus.success.getValue());
		}
		userComment.setUserId(user.getId());
		userComment.setUserName(user.getUsername());
		userComment.setHeadImg(user.getHeadImg());
		userComment.setIfPraise(false); // 新增的评论自己没有点赞
		userComment.setPraise(0); // 新增的评论没有人点赞
		userCommentService.addUserComment(userComment);
		return ReturnResult.success(userComment);
	}
}
